/**
 * 上传进度持久化工具 - 支持断点续传
 * 使用 localStorage 存储上传进度信息
 */

export interface UploadProgressData {
  hash: string;              // 文件hash
  filename: string;          // 文件名
  totalChunks: number;       // 总分片数
  uploadedChunks: number[];  // 已上传的分片索引
  fileSize: number;          // 文件大小
  timestamp: number;         // 最后更新时间
}

const STORAGE_KEY_PREFIX = 'upload_progress_';
const PROGRESS_EXPIRE_DAYS = 7; // 7天后过期

/**
 * 保存上传进度
 */
export function saveUploadProgress(data: UploadProgressData): void {
  try {
    const key = STORAGE_KEY_PREFIX + data.hash;
    const progressData = {
      ...data,
      timestamp: Date.now()
    };
    localStorage.setItem(key, JSON.stringify(progressData));
  } catch (error) {
    console.warn('保存上传进度失败:', error);
  }
}

/**
 * 获取上传进度
 */
export function getUploadProgress(hash: string): UploadProgressData | null {
  try {
    const key = STORAGE_KEY_PREFIX + hash;
    const data = localStorage.getItem(key);
    
    if (!data) {
      return null;
    }
    
    const progressData: UploadProgressData = JSON.parse(data);
    
    // 检查是否过期
    const expireTime = PROGRESS_EXPIRE_DAYS * 24 * 60 * 60 * 1000;
    if (Date.now() - progressData.timestamp > expireTime) {
      // 过期，删除记录
      removeUploadProgress(hash);
      return null;
    }
    
    return progressData;
  } catch (error) {
    console.warn('获取上传进度失败:', error);
    return null;
  }
}

/**
 * 更新已上传的分片
 */
export function updateUploadedChunk(hash: string, chunkIndex: number): void {
  try {
    const progress = getUploadProgress(hash);
    if (progress) {
      // 添加已上传的分片索引（去重）
      if (!progress.uploadedChunks.includes(chunkIndex)) {
        progress.uploadedChunks.push(chunkIndex);
        progress.uploadedChunks.sort((a, b) => a - b);
      }
      saveUploadProgress(progress);
    }
  } catch (error) {
    console.warn('更新上传分片失败:', error);
  }
}

/**
 * 删除上传进度
 */
export function removeUploadProgress(hash: string): void {
  try {
    const key = STORAGE_KEY_PREFIX + hash;
    localStorage.removeItem(key);
  } catch (error) {
    console.warn('删除上传进度失败:', error);
  }
}

/**
 * 清理所有过期的上传进度
 */
export function cleanExpiredProgress(): void {
  try {
    const expireTime = PROGRESS_EXPIRE_DAYS * 24 * 60 * 60 * 1000;
    const now = Date.now();
    
    // 遍历所有localStorage的key
    for (let i = 0; i < localStorage.length; i++) {
      const key = localStorage.key(i);
      if (key && key.startsWith(STORAGE_KEY_PREFIX)) {
        const data = localStorage.getItem(key);
        if (data) {
          try {
            const progressData: UploadProgressData = JSON.parse(data);
            if (now - progressData.timestamp > expireTime) {
              localStorage.removeItem(key);
            }
          } catch {
            // 数据格式错误，直接删除
            localStorage.removeItem(key);
          }
        }
      }
    }
  } catch (error) {
    console.warn('清理过期进度失败:', error);
  }
}

/**
 * 获取所有上传进度
 */
export function getAllUploadProgress(): UploadProgressData[] {
  const progressList: UploadProgressData[] = [];
  
  try {
    for (let i = 0; i < localStorage.length; i++) {
      const key = localStorage.key(i);
      if (key && key.startsWith(STORAGE_KEY_PREFIX)) {
        const data = localStorage.getItem(key);
        if (data) {
          try {
            const progressData: UploadProgressData = JSON.parse(data);
            progressList.push(progressData);
          } catch {
            // 忽略格式错误的数据
          }
        }
      }
    }
  } catch (error) {
    console.warn('获取所有上传进度失败:', error);
  }
  
  return progressList;
}

